<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>公共交通异常检测系统 - 用户登录</title>
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
		<link rel="stylesheet" href="./css/login.css">
		<link rel="icon" href="./img/logo_nobackground.png" type="image/png">
	</head>
	<body>
		<div id="app">
			<!-- 加载遮罩 -->
			<transition name="fade">
				<div v-if="loading" class="loading-overlay">
					<div class="loading-content">
						<div class="loading-spinner">
							<i class="el-icon-loading"></i>
						</div>
						<div>{{ loadingText }}</div>
					</div>
				</div>
			</transition>

			<div class="login-container">
				<!-- 左侧横幅 -->
				<div class="login-banner">
					<div class="banner-content">
						<div class="logo-container">
							<img :src="logoUrl" alt="公共交通异常检测系统" @error="handleLogoError">
						</div>

						<h1 class="banner-title">智行天下，安达万家</h1>
						<p class="banner-subtitle">Smart Travel, Safe and Secure</p>

						<ul class="banner-features">
							<li>实时交通监控与预警</li>
							<li>智能数据分析平台</li>
							<li>全方位安全保障</li>
							<li>高效运营管理</li>
						</ul>
					</div>
				</div>

				<!-- 右侧登录表单 -->
				<div class="login-form">
					<div class="form-header">
						<h2 class="form-title">欢迎回来</h2>
						<p class="form-subtitle">请登录您的账户以继续使用</p>
					</div>

					<div class="login-form-container">
						<el-form :model="loginForm" :rules="loginRules" ref="loginForm"
							@submit.native.prevent="handleLogin">

							<!-- 用户名输入框 -->
							<el-form-item prop="username" class="form-item">
								<el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"
									clearable @keyup.enter.native="handleLogin" :disabled="loading">
								</el-input>
							</el-form-item>

							<!-- 密码输入框 -->
							<el-form-item prop="password" class="form-item">
								<el-input v-model="loginForm.password" type="password" placeholder="请输入密码"
									prefix-icon="el-icon-lock" show-password clearable @keyup.enter.native="handleLogin"
									:disabled="loading">
								</el-input>
							</el-form-item>

							<!-- 登录选项 -->
							<div class="login-options">
								<label class="custom-checkbox remember-me">
									<input type="checkbox" v-model="rememberMe" :disabled="loading">
									<span class="checkmark"></span>
									记住用户名
								</label>
								<a href="#" class="forgot-password" @click.prevent="handleForgotPassword">忘记密码？</a>
							</div>

							<!-- 登录按钮 -->
							<el-button type="primary" class="login-button" :loading="loading" :disabled="!isFormValid"
								@click="handleLogin">
								{{ loading ? loadingText : '登录' }}
							</el-button>
						</el-form>

						<!-- 其他操作 -->
						<div class="other-actions">
							<div class="register-row">
								<span>还没有账户？</span>
								<a href="#" @click.prevent="handleRegister">立即注册</a>
							</div>
						</div>
					</div>

					<!-- 版权信息 -->
					<div class="copyright">
						© {{ currentYear }} 公共交通异常检测系统 · 重庆市北碚区西南大学
					</div>
				</div>
			</div>
		</div>

		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
		<script src="https://unpkg.com/element-ui/lib/index.js"></script>
		<script>
			new Vue({
				el: '#app',
				data() {
					// 自定义验证函数
					const validateUsername = (rule, value, callback) => {
						if (!value) {
							callback(new Error('请输入用户名'));
						} else if (value.length < 3) {
							callback(new Error('用户名至少3个字符'));
						} else if (value.length > 20) {
							callback(new Error('用户名不能超过20个字符'));
						} else {
							callback();
						}
					};

					const validatePassword = (rule, value, callback) => {
						if (!value) {
							callback(new Error('请输入密码'));
						} else if (value.length < 6) {
							callback(new Error('密码至少6个字符'));
						} else if (value.length > 50) {
							callback(new Error('密码不能超过50个字符'));
						} else {
							callback();
						}
					};

					return {
						// 表单数据
						loginForm: {
							username: '',
							password: ''
						},
						// 表单验证规则
						loginRules: {
							username: [{
								validator: validateUsername,
								trigger: 'blur'
							}],
							password: [{
								validator: validatePassword,
								trigger: 'blur'
							}]
						},
						// 状态管理
						loading: false,
						loadingText: '登录中...',
						rememberMe: false,
						// Logo路径
						logoUrl: './img/logo_nobackground.png',
						// 当前年份
						currentYear: new Date().getFullYear(),
						// 预设账户用于演示
						demoAccounts: [
							{
								username: 'admin',
								password: '123456',
								role: '管理员'
							},
							{
								username: 'user',
								password: '123456',
								role: '普通用户'
							},
							{
								username: 'nzp123456',
								password: 'nzp123123',
								role: '普通用户'
							},
							{
								username: 'ts123456',
								password: 'ts123123',
								role: '普通用户'
							}
						]
					}
				},
				computed: {
					isFormValid() {
						return this.loginForm.username.length >= 3 &&
							this.loginForm.password.length >= 6;
					}
				},
				mounted() {
					this.initPage();
				},
				methods: {
					// 页面初始化
					initPage() {
						// 检查是否记住了用户名
						const savedUsername = localStorage.getItem('rememberedUsername');
						if (savedUsername) {
							this.loginForm.username = savedUsername;
							this.rememberMe = true;
						}
					},

					// 处理登录
					async handleLogin() {
						// 表单验证
						const valid = await this.validateForm();
						if (!valid) return;

						this.loading = true;
						this.loadingText = '验证中...';

						try {
							// 模拟登录请求
							const result = await this.performLogin();

							if (result.success) {
								this.loadingText = '登录成功，正在跳转...';

								// 保存登录状态
								this.saveLoginState(result.data);

								// 显示成功消息
								this.$message.success(`欢迎回来，${result.data.username}！`);

								// 延迟跳转到主页
								setTimeout(() => {
									window.location.href = './index.html';
								}, 1500);

							} else {
								this.loading = false;
								this.$message.error(result.message || '登录失败，请检查用户名和密码');
							}
						} catch (error) {
							this.loading = false;
							this.$message.error('登录过程中发生错误，请稍后重试');
							console.error('Login error:', error);
						}
					},

					// 表单验证
					validateForm() {
						return new Promise((resolve) => {
							this.$refs.loginForm.validate((valid) => {
								if (!valid) {
									this.$message.error('请检查表单输入');
								}
								resolve(valid);
							});
						});
					},

					// 执行登录逻辑
					performLogin() {
						return new Promise((resolve) => {
							// 模拟网络延迟
							setTimeout(() => {
								const {
									username,
									password
								} = this.loginForm;

								// 检查预设账户
								const account = this.demoAccounts.find(acc =>
									acc.username === username && acc.password === password
								);

								if (account) {
									resolve({
										success: true,
										data: {
											username: account.username,
											role: account.role,
											token: this.generateToken(),
											loginTime: new Date().toISOString()
										}
									});
								} else {
									resolve({
										success: false,
										message: '用户名或密码错误'
									});
								}
							}, 1000 + Math.random() * 1000); // 1-2秒随机延迟
						});
					},

					// 保存登录状态
					saveLoginState(userData) {
						// 保存认证令牌
						localStorage.setItem('authToken', userData.token);
						localStorage.setItem('userInfo', JSON.stringify(userData));
						localStorage.setItem('loginTime', userData.loginTime);

						// 处理记住用户名
						if (this.rememberMe) {
							localStorage.setItem('rememberedUsername', userData.username);
						} else {
							localStorage.removeItem('rememberedUsername');
						}
					},

					// 生成模拟令牌
					generateToken() {
						return 'token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
					},

					// 处理忘记密码
					handleForgotPassword() {
						this.$alert('请联系系统管理员重置密码<br>邮箱：admin@zhiyuanxing.com<br>电话：023-1234567', '忘记密码', {
							dangerouslyUseHTMLString: true,
							confirmButtonText: '我知道了'
						});
					},

					// 处理注册
					handleRegister() {
						this.$message.info('注册功能开发中，请联系管理员开通账户');
					},

					// 处理Logo加载错误
					handleLogoError() {
						console.warn('Logo image failed to load');
						// 可以设置一个默认的logo或者隐藏logo容器。.
						this.logoUrl =
							'';
					}
				}
			});
		</script>
	</body>
</html>
